package com.lgh.springcloud.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author liugh9
 * @version 1.0
 * @classname MyLb
 * @description
 * @date 2022/06/14 15:53
 */
@Component
public class MyLb implements LoadBalance {

    private AtomicInteger REQUEST_TIME = new AtomicInteger(0);

    @Override
    public ServiceInstance instance(List<ServiceInstance> serviceInstances) {
        int serviceIndex = getAndIncrement() % serviceInstances.size();
        return serviceInstances.get(serviceIndex);
    }

    private final int getAndIncrement() {
        int current;
        int next;
        do {
            current = REQUEST_TIME.get();
            next = current >= Integer.MAX_VALUE ? 0 : current + 1;
        } while (!REQUEST_TIME.compareAndSet(current, next));
        System.out.println("***********第" + next + "次访问***********");
        return next;
    }
}
